package org.example.cotroller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Result;
import org.example.util.ALiOssUtil;
import org.example.util.FileUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api")
public class CommonController {
    @Resource
    private FileUtil fileUtil;

    @Resource
    private ALiOssUtil aliOssUtil;

    /**
     *处理文件上传请求
     **/
    //@PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        log.info("上传照片{}",file.getOriginalFilename());
        String url = fileUtil.uploadFile(file);
        log.info("路径为：{}",url);
        return Result.success(url);
    }

    @PostMapping("/upload")
    //请求中要携带上需要上传的文件
    public Result<String> saveOss(MultipartFile file) {
        try {
            //            获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            //在oss中存储名字就是UUID + 文件的后缀名
            String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String resultURL = aliOssUtil.upload(file.getBytes(), objectName);
            System.out.println(resultURL);
            return Result.success(resultURL);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }




}
